/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tletlis.network;

import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * A class that will act as a client in a Client-Server network.
 * The class has methods for connecting, sending and reciving messages with a
 * server.
 * @author Max
 */
public class Client {
    
    /**
     * The IP-address of the server program
     */
    private String serverIp;
    /**
     * The port to use to connect to server
     */
    private int port;
    /**
     * The clients Socket that will connect to server
     */
    private Socket client;

    /**
     * The constructor initializes the values.
     * Creates a new Client.
     * @param serverIp
     * @param port
     */
    public Client(String serverIp, int port){
            this.serverIp=serverIp;
            this.port=port;
    }
    
    /**
     * Method that will connect client to server
     */
    public void connect(){
        try {
                client = new Socket(serverIp, port);
        } catch (UnknownHostException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Method that returns a message sent to client.
     * If no new message exists null is returned
     * @return String
     */
    public String updateNetwork(){
        String message="0";
        try{
            DataInputStream inStream = new DataInputStream(client.getInputStream());

                //check if there is a new message available on stream
                if(inStream.available()>0){
                    //new message available, read message
                    message=inStream.readUTF();
                }
        }
        catch(IOException ex){
                 Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }

        return message;
    }

    /**
     * Method for sending a message.
     * Takes the parameter and writes it on output stream.
     * returns true if message is sent, else returns false
     * @param message
     * @return boolean
     */
    public boolean send(String message){
        boolean isSent=false;
        try {

           DataOutputStream out = new DataOutputStream(client.getOutputStream());
           //write message on stream
           out.writeUTF(message);
           //message is sent
           isSent=true;

        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        return isSent;
    }

}
